<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="工单编号" prop="taskNo">
        <el-input
          v-model="queryParams.taskNo"
          placeholder="请输入工单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单类型" prop="taskTypeId">
        <el-select v-model="queryParams.taskTypeId" placeholder="请选择工单类型" clearable>
          <el-option label="投放工单" :value="1" />
          <el-option label="维修工单" :value="2" />
          <el-option label="补货工单" :value="3" />
          <el-option label="撤机工单" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="工单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择工单状态" clearable>
          <el-option label="待处理" :value="0" />
          <el-option label="进行中" :value="1" />
          <el-option label="已完成" :value="2" />
          <el-option label="已取消" :value="3" />
          <el-option label="已关闭" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备编号" prop="deviceCode">
        <el-input
          v-model="queryParams.deviceCode"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="执行人" prop="assigneeName">
        <el-input
          v-model="queryParams.assigneeName"
          placeholder="请输入执行人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:task:add']"
        >新增工单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:task:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:task:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工单编号" align="center" prop="taskNo" width="180" />
      <el-table-column label="工单类型" align="center" prop="taskTypeName" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.taskTypeId === 1" type="primary">投放工单</el-tag>
          <el-tag v-else-if="scope.row.taskTypeId === 2" type="warning">维修工单</el-tag>
          <el-tag v-else-if="scope.row.taskTypeId === 3" type="success">补货工单</el-tag>
          <el-tag v-else-if="scope.row.taskTypeId === 4" type="danger">撤机工单</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="工单状态" align="center" prop="statusName" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="info">待处理</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="primary">进行中</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="success">已完成</el-tag>
          <el-tag v-else-if="scope.row.status === 3" type="danger">已取消</el-tag>
          <el-tag v-else-if="scope.row.status === 4" type="info">已关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="设备编号" align="center" prop="deviceCode" width="150" />
      <el-table-column label="设备名称" align="center" prop="deviceName" show-overflow-tooltip />
      <el-table-column label="执行人" align="center" prop="assigneeName" width="100" />
      <el-table-column label="区域" align="center" prop="regionName" width="120" />
      <el-table-column label="优先级" align="center" prop="priority" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.priority === 1" type="danger">高</el-tag>
          <el-tag v-else-if="scope.row.priority === 2" type="warning">中</el-tag>
          <el-tag v-else-if="scope.row.priority === 3" type="info">低</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="View"
            @click="handleView(scope.row)"
            v-hasPermi="['manage:task:query']"
          >查看</el-button>
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:task:edit']"
            v-if="scope.row.status === 0 || scope.row.status === 1"
          >修改</el-button>
          <el-button
            link
            type="warning"
            icon="CircleClose"
            @click="handleCancel(scope.row)"
            v-hasPermi="['manage:task:cancel']"
            v-if="scope.row.status === 0 || scope.row.status === 1"
          >取消</el-button>
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:task:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工单对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="taskRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单类型" prop="taskTypeId">
              <el-select v-model="form.taskTypeId" placeholder="请选择工单类型">
                <el-option label="投放工单" :value="1" />
                <el-option label="维修工单" :value="2" />
                <el-option label="补货工单" :value="3" />
                <el-option label="撤机工单" :value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级">
                <el-option label="高" :value="1" />
                <el-option label="中" :value="2" />
                <el-option label="低" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备" prop="deviceId">
              <el-select v-model="form.deviceId" placeholder="请选择设备" filterable>
                <el-option
                  v-for="item in deviceList"
                  :key="item.id"
                  :label="item.innerCode + ' - ' + item.nodeName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行人" prop="assigneeId">
              <el-select v-model="form.assigneeId" placeholder="请选择执行人" filterable>
                <el-option
                  v-for="item in empList"
                  :key="item.id"
                  :label="item.userName + ' (' + item.regionName + ')'"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工单描述" prop="description">
              <el-input
                v-model="form.description"
                type="textarea"
                :rows="3"
                placeholder="请输入工单描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="2"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看工单详情对话框 -->
    <el-dialog title="工单详情" v-model="viewOpen" width="900px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="工单编号">{{ viewForm.taskNo }}</el-descriptions-item>
        <el-descriptions-item label="工单类型">
          <el-tag v-if="viewForm.taskTypeId === 1" type="primary">投放工单</el-tag>
          <el-tag v-else-if="viewForm.taskTypeId === 2" type="warning">维修工单</el-tag>
          <el-tag v-else-if="viewForm.taskTypeId === 3" type="success">补货工单</el-tag>
          <el-tag v-else-if="viewForm.taskTypeId === 4" type="danger">撤机工单</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="工单状态">
          <el-tag v-if="viewForm.status === 0" type="info">待处理</el-tag>
          <el-tag v-else-if="viewForm.status === 1" type="primary">进行中</el-tag>
          <el-tag v-else-if="viewForm.status === 2" type="success">已完成</el-tag>
          <el-tag v-else-if="viewForm.status === 3" type="danger">已取消</el-tag>
          <el-tag v-else-if="viewForm.status === 4" type="info">已关闭</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="优先级">
          <el-tag v-if="viewForm.priority === 1" type="danger">高</el-tag>
          <el-tag v-else-if="viewForm.priority === 2" type="warning">中</el-tag>
          <el-tag v-else-if="viewForm.priority === 3" type="info">低</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="设备编号">{{ viewForm.deviceCode }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ viewForm.deviceName }}</el-descriptions-item>
        <el-descriptions-item label="执行人">{{ viewForm.assigneeName }}</el-descriptions-item>
        <el-descriptions-item label="区域">{{ viewForm.regionName }}</el-descriptions-item>
        <el-descriptions-item label="工单描述" :span="2">{{ viewForm.description }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(viewForm.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ viewForm.createBy }}</el-descriptions-item>
        <el-descriptions-item label="取消原因" :span="2" v-if="viewForm.status === 3">
          {{ viewForm.cancelReason }}
        </el-descriptions-item>
        <el-descriptions-item label="取消时间" v-if="viewForm.status === 3">
          {{ parseTime(viewForm.cancelTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="取消人" v-if="viewForm.status === 3">
          {{ viewForm.cancelBy }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ viewForm.remark }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 取消工单对话框 -->
    <el-dialog title="取消工单" v-model="cancelOpen" width="500px" append-to-body>
      <el-form :model="cancelForm" :rules="cancelRules" ref="cancelRef" label-width="100px">
        <el-form-item label="取消原因" prop="cancelReason">
          <el-input
            v-model="cancelForm.cancelReason"
            type="textarea"
            :rows="4"
            placeholder="请输入取消原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCancel">确 定</el-button>
          <el-button @click="cancelOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Task">
import { listTask, getTask, delTask, addTask, updateTask, cancelTask } from "@/api/manage/task";
import { listVendingMachine } from "@/api/manage/vendingMachine";
import { listEmp } from "@/api/manage/emp";

const { proxy } = getCurrentInstance();

const taskList = ref([]);
const deviceList = ref([]);
const empList = ref([]);
const open = ref(false);
const viewOpen = ref(false);
const cancelOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  viewForm: {},
  cancelForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskNo: null,
    taskTypeId: null,
    status: null,
    deviceCode: null,
    assigneeName: null
  },
  rules: {
    taskTypeId: [
      { required: true, message: "工单类型不能为空", trigger: "change" }
    ],
    deviceId: [
      { required: true, message: "设备不能为空", trigger: "change" }
    ],
    assigneeId: [
      { required: true, message: "执行人不能为空", trigger: "change" }
    ],
    priority: [
      { required: true, message: "优先级不能为空", trigger: "change" }
    ]
  },
  cancelRules: {
    cancelReason: [
      { required: true, message: "取消原因不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, viewForm, cancelForm, rules, cancelRules } = toRefs(data);

/** 查询工单列表 */
function getList() {
  loading.value = true;
  listTask(queryParams.value).then(response => {
    taskList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 加载设备列表 */
function loadDeviceList() {
  listVendingMachine({}).then(response => {
    deviceList.value = response.rows;
  });
}

/** 加载员工列表 */
function loadEmpList() {
  listEmp({}).then(response => {
    empList.value = response.rows;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    taskTypeId: null,
    deviceId: null,
    assigneeId: null,
    description: null,
    priority: 2,
    remark: null
  };
  proxy.resetForm("taskRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  loadDeviceList();
  loadEmpList();
  open.value = true;
  title.value = "新增工单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  loadDeviceList();
  loadEmpList();
  const id = row.id || ids.value[0];
  getTask(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改工单";
  });
}

/** 查看按钮操作 */
function handleView(row) {
  getTask(row.id).then(response => {
    viewForm.value = response.data;
    viewOpen.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["taskRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateTask(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTask(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 取消工单按钮 */
function handleCancel(row) {
  cancelForm.value = {
    id: row.id,
    taskNo: row.taskNo,
    cancelReason: ''
  };
  cancelOpen.value = true;
}

/** 提交取消工单 */
function submitCancel() {
  proxy.$refs["cancelRef"].validate(valid => {
    if (valid) {
      cancelTask(cancelForm.value.id, cancelForm.value.cancelReason).then(response => {
        proxy.$modal.msgSuccess("工单取消成功");
        cancelOpen.value = false;
        getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const taskIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除工单编号为"' + (row.taskNo || taskIds) + '"的数据项？').then(function() {
    return delTask(taskIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/task/export', {
    ...queryParams.value
  }, `task_${new Date().getTime()}.xlsx`)
}

getList();
</script>
